<template>
  <div class="app-container home">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :xs="12" :sm="6" :lg="6" class="card-panel-col">
        <el-card class="card-panel">
          <div class="card-panel-icon-wrapper icon-production">
            <i class="el-icon-s-promotion card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">服务个数</div>
            <count-to :start-val="0" :end-val="statistics.totalOrders" :duration="2600" class="card-panel-num" />
            <div class="card-panel-sub-text">今日服务量: {{ statistics.todayOrders }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="6" class="card-panel-col">
        <el-card class="card-panel">
          <div class="card-panel-icon-wrapper icon-shop">
            <i class="el-icon-s-shop card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">接单个数</div>
            <count-to :start-val="0" :end-val="statistics.totalAccepted" :duration="2600" class="card-panel-num" />
            <div class="card-panel-sub-text">今日接单量: {{ statistics.todayAccepted }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="6" class="card-panel-col">
        <el-card class="card-panel">
          <div class="card-panel-icon-wrapper icon-money">
            <i class="el-icon-money card-panel-icon"></i>
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">总销售额</div>
            <count-to :start-val="0" :end-val="statistics.totalSales" :duration="2600" class="card-panel-num" />
            <div class="card-panel-sub-text">今日销售额: ¥{{ statistics.todaySales.toFixed(2) }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :lg="16">
        <el-card>
          <div slot="header" class="clearfix">
            <span>平台月订单量</span>
          </div>
          <div class="chart-wrapper">
            <div id="lineChart" style="height: 350px;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="8">
        <el-card>
          <div slot="header" class="clearfix">
            <span>平台订单占比</span>
          </div>
          <div class="chart-wrapper">
            <div id="pieChart" style="height: 350px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-divider />

    <!-- 最近订单和快捷入口 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :lg="16">
        <el-card>
          <div slot="header" class="clearfix">
            <span>最近日订单</span>
          </div>
          <el-table :data="latestOrders" style="width: 100%">
            <el-table-column prop="orderId" label="订单编号"></el-table-column>
            <el-table-column prop="paymentMethod" label="支付方式"></el-table-column>
            <el-table-column prop="totalAmount" label="订单总额"></el-table-column>
            <el-table-column prop="shippingAddress" label="收货地址"></el-table-column>
            <el-table-column prop="paymentStatus" label="支付状态"></el-table-column>
            <el-table-column prop="paymentTime" label="支付时间"></el-table-column>
            <el-table-column prop="orderRemark" label="订单备注"></el-table-column>
            <el-table-column prop="dailyOrderCount" label="当日订单数"></el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import * as echarts from 'echarts'
import { getOrdersCount, getOrdersCountByStatus, getTotalSales, getMonthlyOrders, getRecentDailyOrders, getPaymentMethodDistribution } from "@/api/home/order"

export default {
  name: "Index",
  components: { CountTo },
  data() {
    return {
      // 版本号
      version: "3.6.6",
      // 统计数据
      statistics: {
        totalOrders: 0,
        todayOrders: 0,
        totalAccepted: 0,
        todayAccepted: 0,
        totalSales: 0,
        todaySales: 0
      },
      // 图表实例
      lineChart: null,
      pieChart: null,
      // 新增：月度订单数据
      monthlyOrderData: {
        months: [],
        orderCounts: []
      },
      latestOrders: [],
      // 新增：支付方式分布数据
      paymentDistributionData: [],
      // 新增：分页参数
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 新增：支付方式映射
      paymentMethodsMap: {
        1: '微信',
        2: '余额',
      },
      // 新增：订单状态映射
      orderStatusesMap: {
        1: '待支付',
        2: '待服侍',
        3: '服侍中',
        4: '待评价',
        5: '待完成',
        6: '已取消',
        7: '已退款'
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initPieChart()
    })
    this.getStatistics()
    this.getRecentDailyOrdersList()
  },
  beforeDestroy() {
    if (this.lineChart) {
      this.lineChart.dispose()
      window.removeEventListener('resize', this.lineChart.resize);
    }
    if (this.pieChart) {
      this.pieChart.dispose()
    }
  },
  methods: {
    // 获取统计数据
    getStatistics() {
      // 获取服务个数
      getOrdersCount().then(response => {
        this.statistics.totalOrders = response.data.total || 0
        this.statistics.todayOrders = response.data.today || 0
      }).catch(error => {
        console.error('获取服务个数失败:', error)
        this.statistics.totalOrders = 1248760
        this.statistics.todayOrders = 12450
      })

      // 获取接单个数 (状态2表示已接单)
      getOrdersCountByStatus(2).then(response => {
        this.statistics.totalAccepted = response.data.total || 0
        this.statistics.todayAccepted = response.data.today || 0
      }).catch(error => {
        console.error('获取接单个数失败:', error)
        this.statistics.totalAccepted = 387650
        this.statistics.todayAccepted = 2370
      })

      // 获取销售总额
      getTotalSales().then(response => {
        this.statistics.totalSales = response.data.total || 0
        this.statistics.todaySales = response.data.today || 0
      }).catch(error => {
        console.error('获取销售总额失败:', error)
        this.statistics.totalSales = 5764920
        this.statistics.todaySales = 548930
      })

      // 获取平台月订单量
      getMonthlyOrders().then(response => {
        if (response.code === 200 && response.data) {
          const months = response.data.map(item => item.month);
          const orderCounts = response.data.map(item => item.orderCount);
          this.monthlyOrderData.months = months;
          this.monthlyOrderData.orderCounts = orderCounts;
          this.initLineChart();
        }
      }).catch(error => {
        console.error('获取平台月订单量失败:', error);
        this.monthlyOrderData.months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        this.monthlyOrderData.orderCounts = [1000, 1200, 1500, 1300, 1800, 2000, 2200, 2500, 2300, 2100, 1900, 1700];
        this.initLineChart();
      });

      // 获取平台订单支付方式分布数据
      getPaymentMethodDistribution().then(response => {
        if (response.code === 200 && response.data) {
          // 映射数据以适应ECharts饼图的 {name: '名称', value: 数量} 格式
          this.paymentDistributionData = response.data.map(item => ({
            name: this.paymentMethodsMap[item.paymentMethod] || '未知',
            value: item.orderCount
          }));
          this.initPieChart(); // 数据加载后更新饼图
        }
      }).catch(error => {
        console.error('获取支付方式分布数据失败:', error);
        // 失败时提供一些模拟数据
        this.paymentDistributionData = [
          { name: '微信 (模拟)', value: 70 },
          { name: '余额 (模拟)', value: 30 }
        ];
        this.initPieChart(); // 即使失败也尝试初始化图表，用模拟数据
      });
    },
    getRecentDailyOrdersList() {
      getRecentDailyOrders(this.queryParams).then(response => {
        if (response.code === 200 && response.rows) {
          this.latestOrders = response.rows.map(item => ({
            orderId: item['订单编号'],
            paymentMethod: this.paymentMethodsMap[item['支付方式']] || item['支付方式'],
            totalAmount: item['订单总额'],
            shippingAddress: item['收货地址'],
            paymentStatus: this.orderStatusesMap[item['订单状态']] || item['订单状态'],
            paymentTime: item['支付时间'],
            orderRemark: item['订单备注'] || '无',
            dailyOrderCount: item['当日订单数']
          }));
          this.total = response.total;
        }
      }).catch(error => {
        console.error('获取最近日订单数据失败:', error);
        this.latestOrders = [
          {
            orderId: 'ORD_MOCK_001',
            paymentMethod: '模拟支付',
            totalAmount: '¥100.00',
            shippingAddress: '模拟地址',
            paymentStatus: '模拟状态',
            paymentTime: '2024-01-01 12:00:00',
            orderRemark: '模拟备注',
            dailyOrderCount: 0
          }
        ];
        this.total = 1;
      });
    },
    handleSizeChange(newSize) {
      this.queryParams.pageSize = newSize;
      this.getRecentDailyOrdersList();
    },
    handleCurrentChange(newPage) {
      this.queryParams.pageNum = newPage;
      this.getRecentDailyOrdersList();
    },
    initLineChart() {
      const chartDom = document.getElementById('lineChart')
      if (!chartDom) return

      if (this.lineChart) {
        this.lineChart.dispose();
      }
      this.lineChart = echarts.init(chartDom)
      const option = {
        title: {
          text: '平台月订单量',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c} 单'
        },
        xAxis: {
          type: 'category',
          data: this.monthlyOrderData.months,
          axisLabel: {
            interval: 0,
            rotate: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '订单量',
          axisLabel: {
            formatter: '{value} 单'
          }
        },
        series: [
          {
            name: '订单量',
            type: 'line',
            data: this.monthlyOrderData.orderCounts,
            smooth: true,
            itemStyle: {
              color: '#1890ff'
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        }
      };
      this.lineChart.setOption(option);
      window.addEventListener('resize', this.lineChart.resize);
    },
    initPieChart() {
      const chartDom = document.getElementById('pieChart')
      if (!chartDom) return

      if (this.pieChart) {
        this.pieChart.dispose(); // 销毁旧实例
      }
      this.pieChart = echarts.init(chartDom)
      const option = {
        title: {
          text: '平台订单占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.paymentDistributionData.map(item => item.name) // 使用动态数据的名称作为图例
        },
        series: [
          {
            name: '支付方式',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: this.paymentDistributionData, // 使用动态数据
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.pieChart.setOption(option);
      // 添加 resize 监听器
      window.addEventListener('resize', this.pieChart.resize);
    },
    goTarget(href) {
      window.open(href, "_blank")
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  .panel-group {
    margin-top: 10px;

    .card-panel-col {
      margin-bottom: 32px;
    }

    .card-panel {
      height: 108px;
      cursor: pointer;
      font-size: 12px;
      position: relative;
      overflow: hidden;
      color: #666;
      background: #fff;
      box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
      border-color: rgba(0, 0, 0, .05);

      &:hover {
        .card-panel-icon-wrapper {
          color: #fff;
        }

        .icon-production {
          background: #40c9c6;
        }

        .icon-order {
          background: #36a3f7;
        }

        .icon-shop {
          background: #f4516c;
        }

        .icon-money {
          background: #34bfa3;
        }
      }

      .icon-production {
        color: #40c9c6;
      }

      .icon-order {
        color: #36a3f7;
      }

      .icon-shop {
        color: #f4516c;
      }

      .icon-money {
        color: #34bfa3
      }

      .card-panel-icon-wrapper {
        float: left;
        margin: 14px 0 0 14px;
        padding: 16px;
        transition: all 0.38s ease-out;
        border-radius: 6px;
      }

      .card-panel-icon {
        float: left;
        font-size: 48px;
      }

      .card-panel-description {
        float: right;
        font-weight: bold;
        margin: 26px;
        margin-left: 0px;

        .card-panel-text {
          line-height: 18px;
          color: rgba(0, 0, 0, 0.45);
          font-size: 16px;
          margin-bottom: 12px;
        }

        .card-panel-num {
          font-size: 24px;
        }

        .card-panel-sub-text {
          font-size: 14px;
          color: #999;
          margin-top: 5px;
        }
      }
    }
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 15px;
  }

  .quick-entry-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
    margin-bottom: 20px;
  }
}
</style>

